/**
 * 
 */
package freedom.needle.sleep;

import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freedom.needle.util.CalendarUtil;

/**
 * @author charlie
 *
 */
public class SleepWindowDeamon implements Runnable{
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private long interval = 1000;//刷新时间间隔
	private SleepWindow sleepWindow;

	/**
	 * @param interval
	 * @param sleepWindow
	 */
	public SleepWindowDeamon(long interval, SleepWindow sleepWindow) {
		super();
		this.interval = interval;
		this.sleepWindow = sleepWindow;
	}

	@Override
	public void run() {
		while (true) {
			try {
				refresh();
				Thread.sleep(interval);
			} catch (InterruptedException e) {
				logger.warn("sleep is interrupted!");
			} catch(Exception e) {
				logger.error("refresh error!");
			}
		}
		
	}
	
	private void refresh() {
		boolean open = true;//true-进入休眠窗口
		Calendar now = Calendar.getInstance();
		if(sleepWindow.getLeft().equals(sleepWindow.getRight()))
			open = false;
		else if(sleepWindow.getLeft().before(sleepWindow.getRight())) {
			Calendar a = CalendarUtil.mixCalendar(now, sleepWindow.getLeft());
			Calendar b = CalendarUtil.mixCalendar(now, sleepWindow.getRight());
			open = now.after(a) && now.before(b);
		} else {
			Calendar a = CalendarUtil.zeroClock(now, false);
			Calendar b = CalendarUtil.mixCalendar(now, sleepWindow.getRight());
			Calendar c = CalendarUtil.mixCalendar(now, sleepWindow.getLeft());
			Calendar d = CalendarUtil.zeroClock(now, true);
			open = now.after(a) && now.before(b) || now.after(c) && now.before(d);
		}
		
		if(open) {
			sleepWindow.open();
			if(logger.isDebugEnabled()) {
				logger.debug("sleepWindow open.");
			}
		} else {
			sleepWindow.close();
			logger.debug("sleepWindow close.");
		}
		
	}
	

}
